package com.elinshaw.netty4.config

import cn.hutool.core.date.DateUtil
import com.elinshaw.netty4.utils.Constant
import groovy.util.logging.Slf4j
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent

/**
 * @author Administrator
 */
@Slf4j
class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    /** 空闲次数 */
    private int idleCount = 1

    /**循环次数 */
    private int loopCount = 1

    /**
     * 心跳请求处理
     * 每4秒发送一次心跳请求;
     */
    @Override
    void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
        log.info("循环请求时间{}次数{}", DateUtil.now(), loopCount)
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj
            if (IdleState.WRITER_IDLE == event.state()) {
                if (idleCount <= 3) {
                    idleCount++
                    ctx.channel().writeAndFlush(Constant.HEART_BEAT)
                } else {
                    log.info("不再发送心跳")
                }
                loopCount++
            }
        }
    }

}
